package org.summerframework.component.security.spring.config;

import org.summerframework.component.security.context.RequestContext;
import org.summerframework.component.security.spring.LoginSecurityData;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;

/**
 * @author 石超
 * @version v1.0.0
 */
public class RequestContextConfigurer<H extends HttpSecurityBuilder<H>> extends
        AbstractHttpConfigurer<RequestContextConfigurer<H>, H> {
    @Override
    public void configure(H builder) throws Exception {
        builder.addFilterAfter((request, response, chain) -> {
            final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication instanceof OAuth2Authentication && authentication.isAuthenticated()) {
                final LoginSecurityData userAuthentication = (LoginSecurityData) ((OAuth2Authentication) authentication).getUserAuthentication();
                RequestContext.getContext().setLoginData(userAuthentication.getLoginData());
            }
            chain.doFilter(request, response);
        }, OAuth2AuthenticationProcessingFilter.class);
    }
}
